//
//  HWTeaCalendarCell.m
//  HuaWan
//
//  Created by HuaWan on 2022.
//  Copyright © 2022年 HuaWan. All rights reserved.
//

#import "HWTeaCalendarCell.h"

@implementation HWTeaCalendarCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setData:(id)data delegate:(id)delegate {
    _delegate = delegate;
    
    if ([data isKindOfClass:[NSDictionary class]]) {
        if ([data[@"data"] isKindOfClass:[HWTeaCalendarCellModel class]]) {
            HWTeaCalendarCellModel *model = data[@"data"];
            _model = model;

            //移除之前的子控件
            [_myView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
            
            float width = (kScreenWidth - 25*2) / 5;

            NSArray *calendarAry = [HWTeaCalendarCell calendarStringForDate:model.month];
            NSLog(@"=============== %@",calendarAry);
            
            __block NSInteger lincount = 0;
            
            [calendarAry enumerateObjectsUsingBlock:^(NSString *str, NSUInteger idx, BOOL * _Nonnull stop) {
                UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0,width,width)];
                view.backgroundColor = [UIColor clearColor];
                NSString *date;

                NSArray *array = [str componentsSeparatedByString:@" "];
                if (array.count >= 2) {
                    date = array[1];
                }
                
                //用于格式化NSDate对象
                NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                formatter.dateFormat = @"yyyy-MM-dd";
                NSString *longDateStr = [NSString stringWithFormat:@"%@-%@",model.month,date];
                NSDate *dayDate = [formatter dateFromString:longDateStr];
                
                HWTeaModel *teaModel = [kDataManager querTeaDataDicWithDate:[formatter stringFromDate:dayDate]];
                
                if (teaModel.ico.length > 0) {
                    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                    button.frame = view.frame;
                    [button setImage:[UIImage imageNamed:teaModel.ico] forState:UIControlStateNormal];
                    [button addTarget:self action:@selector(calendarButtonAction:) forControlEvents:UIControlEventTouchUpInside];
                    [view addSubview:button];
                } else {
                    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                    button.frame = view.frame;
                    [button setImage:[UIImage imageNamed:@"two_tea"] forState:UIControlStateNormal];
                    [view addSubview:button];
                }

                NSInteger i = idx % 5;
                
                view.frame = CGRectMake(width*i,width*lincount,width,width);
                
                UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(view.frame.size.width/2 - 32/2, view.frame.size.height/2 - 32/2 + 5, 32, 32)];
                label.text = date;
                label.textAlignment = NSTextAlignmentCenter;
                label.font = [UIFont boldSystemFontOfSize:14];
                label.textColor = UIColorFromHex(0x000000);
                
                [view addSubview:label];
                
                if (teaModel && !teaModel.isCustom) {
                    label.hidden = YES;
                }

                [_myView addSubview:view];
                
                if (idx % 5 == 4) {
                    lincount ++;
                }
            }];
        }
    }
}

+ (NSArray *)calendarStringForDate:(NSString *)currentMonth {
    NSDateFormatter *dateF = [[NSDateFormatter alloc] init];
    [dateF setDateFormat:@"yyyy-MM"];
    NSDate *d = [dateF dateFromString:currentMonth];
    [dateF setDateFormat:@"yyyy"];
    NSInteger year = [[dateF stringFromDate:d] integerValue];
    [dateF setDateFormat:@"MM"];
    NSInteger month = [[dateF stringFromDate:d] integerValue];
    
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [[NSDateComponents alloc] init];
    components.year = year;
    components.month = month;
    
    NSDate *startDate = [calendar dateFromComponents:components];
    
    NSRange daysRange = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:startDate];
    
    NSDateFormatter *weekdayFormatter = [[NSDateFormatter alloc] init];
    weekdayFormatter.dateFormat = @"EEE";
    NSDateFormatter *dayFormatter = [[NSDateFormatter alloc] init];
    dayFormatter.dateFormat = @"dd";
    
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    if ([@"Language" isEqualToString:@"EN"]) {
        locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en"];
    }
    weekdayFormatter.locale = locale;
    dayFormatter.locale = locale;
    
    NSMutableArray *calendarAry = [NSMutableArray arrayWithCapacity:30];
    
    for (NSInteger i = 0; i < daysRange.length; i++) {
        NSDate *date = [calendar dateByAddingUnit:NSCalendarUnitDay value:i toDate:startDate options:0];
        NSString *weekdayString = [weekdayFormatter stringFromDate:date];
        NSString *dayString = [dayFormatter stringFromDate:date];
        
        NSString *rowString = [NSString stringWithFormat:@"%@ %@", weekdayString, dayString];
        [calendarAry addObject:rowString];
    }
    return calendarAry;
}

- (void)calendarButtonAction:(UIButton *)sender {
    if (_delegate && [_delegate respondsToSelector:@selector(teaCalendarCell:button:)]) {
        [_delegate teaCalendarCell:self button:sender];
    }
}

+ (float)getCellFrame:(id)msg {
    
    if ([msg isKindOfClass:[HWTeaCalendarCellModel class]]) {
        HWTeaCalendarCellModel *model = msg;
        
        NSArray *calendarAry = [HWTeaCalendarCell calendarStringForDate:model.month];
        
        NSInteger i = calendarAry.count % 5;
        NSInteger j = calendarAry.count / 5;
        
        float width = (kScreenWidth - 25*2) / 5;
        if (i > 0) {
            return (j + 1)*width + 20;
        } else {
            return j*width + 20;
        }
    }
    return 60;
}

@end


#pragma mark - Model

@implementation HWTeaCalendarCellModel

+ (HWTeaCalendarCellModel *)ittemModelWithMonth:(NSString *)month selectDay:(NSString *)selectDay {
    HWTeaCalendarCellModel *model = [HWTeaCalendarCellModel new];
    model.month = kSafeString(month);
    model.selectDay = kSafeString(selectDay);
    return model;
}

@end
